package com.example.demo.pay;

import com.example.demo.repo.RepertoryCache;
import com.example.demo.repo.RepertoryRepo;
import com.example.demo.repo.Repo;
import com.example.demo.repo.model.Order;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

import static com.example.demo.common.Constant.ORDER_PREVIEW_CONSUMER_GROUP;
import static com.example.demo.common.Constant.ORDER_TO_PAY;

@Service
@RocketMQMessageListener(topic = ORDER_TO_PAY,
        consumerGroup = ORDER_PREVIEW_CONSUMER_GROUP + "2")
public class PayTimeoutService implements RocketMQListener<Order> {

    @Override
    public void onMessage(Order message) {

        Optional<Order> optionalOrder = repo.getOrder(message.getOrderId());
        if (!optionalOrder.isPresent()) {
            // 订单不存在，打印日志
            return;
        };

        Order order = optionalOrder.get();
        if (order.getOrderStatus() == Order.OrderStatus.not_pay) {
            // 还未支付，设为超时并释放库存
            order.setOrderStatus(Order.OrderStatus.timeout);
            order.setUpdateTime(new Date().getTime());
            order.setMsg("超时 " + (order.getUpdateTime() - order.getCreateTime()));
            repo.putOrder(order);

            repertoryRepo.takeOut(order.getProductId(), -1 * order.getNumbers());
            cache.takeOut(order.getProductId(), -1 * order.getNumbers());
        }
    }

    private Repo repo;
    private RepertoryCache cache;
    private RepertoryRepo repertoryRepo;

    public PayTimeoutService(Repo repo, RepertoryCache cache, RepertoryRepo repertoryRepo) {
        this.repo = repo;
        this.cache = cache;
        this.repertoryRepo = repertoryRepo;
    }
}
